import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { filter, switchMap } from 'rxjs/operators';
import { UserService } from '@services/user.service';
import { Hero } from '@configs/types';
import { AuthKey } from '@configs/constant';
import { AccountService } from '@services/account.service';
import { WindowService } from '@services/window.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [UserService],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HomeComponent implements OnInit {
  breadCrumbs: string[];
  currentUser: Hero;
  showDropMenu: boolean;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private userServe: UserService,
    private accountServe: AccountService,
    private windowServe: WindowService
  ) {
    this.router.events.pipe((
      filter(event => event instanceof NavigationEnd),
        switchMap(() => {
          return this.route.firstChild.data;
        })
    )).subscribe((data) => {
      this.breadCrumbs = data.breadcrumb;
    });
  }

  ngOnInit() {
    this.refreshUser();
  }
  logout(): void {
    this.accountServe.logout().subscribe(() => {
      window.localStorage.removeItem(AuthKey);
      this.userServe.clearUser();
      this.router.navigateByUrl('/login').then(() => {
        this.windowServe.alert('退出成功');
      });
    });
  }
  private refreshUser(): void {
    this.userServe.user$.subscribe(currentUser => {
      const authKey = window.localStorage.getItem(AuthKey);
      if (!currentUser && authKey) {
        this.accountServe.account().subscribe(({user, token}) => {
          window.localStorage.setItem(AuthKey, token);
          this.userServe.setUser(user);
          this.currentUser = user;
        });
      }
    });
  }
}
